package com.ssm.demo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.demo.dao.BookDao;
import com.ssm.demo.pojo.Book;
import com.ssm.demo.pojo.PageBean;
import com.ssm.demo.pojo.VO.ResultVO;
import com.ssm.demo.service.BookService;
import com.ssm.demo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public ResultVO<PageBean<Book>> getBooks(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<Book> books = bookDao.selectAllBooks();

        PageInfo<Book> pageInfo = new PageInfo<>(books);

        PageBean<Book> pageBean = new PageBean<>(
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getPages(),
                pageInfo.getPrePage(),
                pageInfo.getNextPage(),
                pageInfo.getList());

        return R.successR(pageBean);
    }

    @Override
    public ResultVO<Integer> delBook(Integer bookId) {
        int i = bookDao.deleteById(bookId);
        if (i > 0){
            return R.successR(i);
        }
        return R.errorR(R.ResponseStatus.FAILURE);
    }

    @Override
    public ResultVO<Book> addBook(Book book) {
        Integer i = bookDao.insertBook(book);
        book.setBookId(i);
        return i == null ? R.errorR(R.ResponseStatus.FAILURE) : R.successR(book);
    }
}
